package com.example.chatclient;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChatClient extends Activity implements OnInitListener {
	private final static String IP = // IP 주소 지정 (1）
	"192.168.1.107";

	private TextView textView1;// 수신 라벨
	
	private ListView listViewChat;// 수신 라벨
	private ArrayAdapter<String> mChatArrayAdapter;

	private EditText editTextInput; // 송신 텍스트 박스

	private Handler handler = new Handler();// 핸들러 （6）

	// private ChattingService chattingService;
	// private ReceiveService receiveService;
	private ReceiveService receiveService;
	private SendService sendService;

	Socket socket = null;

	public static String KeyLocation = "#LCT";
	public static String KeyNickname = "#NCK";
	public static String KeyRoomMake = "#RMK";
	public static String KeyDisconnect = "#DCN";
	public static String KeyMessage = "#MSG";
	public static String KeyRoomJoin = "#RJN";

	private TextToSpeech mTTS; // TextToSpeech 객체
	private ArrayList<Locale> mLanguages; // 사용할 언어(국가)
	
	// 초기화
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main);

		textView1 = (TextView) findViewById(R.id.textView1);
		textView1.setVisibility(View.INVISIBLE);
		
		listViewChat = (ListView) findViewById(R.id.listViewChat);
		mChatArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.textstylexml);
		listViewChat.setAdapter(mChatArrayAdapter);

		editTextInput = (EditText) findViewById(R.id.editTextInput);

		mTTS = new TextToSpeech(this, this); // tts 객체 생성
		mLanguages = new ArrayList<Locale>(); // 사용할 언어 리스트 생성
		mLanguages.add(Locale.US); // 영어
		mLanguages.add(Locale.KOREA); // 한국어
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				String message = (String) msg.obj;
				StringTokenizer seperation = new StringTokenizer(message, ",");
				String keyCode = seperation.nextToken();

				if (keyCode.equals(KeyMessage)) {
					String voiceString = seperation.nextToken();
					
					mChatArrayAdapter.add(voiceString);
					
					textView1.setText(voiceString);
					textView1.setVisibility(View.VISIBLE);
					
					// repeat input voice
					Locale lang = mLanguages.get(0); // English
					mTTS.setLanguage(lang); // 언어 설정.
					mTTS.setPitch(1); // pitch 설정.
					mTTS.setSpeechRate(1); // rate 설정.
					mTTS.speak(voiceString, TextToSpeech.QUEUE_FLUSH, null);
				}
			}
		};

		new ReceiveTask().execute("192.168.1.107", "50000");
	}

	public void onButtonSend(View v) {
		if(!editTextInput.getText().toString().trim().equals(""))
			new SendTask().execute(KeyMessage + ","
					+ editTextInput.getText().toString());
	}

	private class ReceiveTask extends AsyncTask<String, Void, Void> {
		// params comes from the execute() call
		@Override
		protected Void doInBackground(String... params) {
			try {
				receiveService = new ReceiveService(params[0],
						Integer.parseInt(params[1]));
				socket = receiveService.getSocket();

				if(socket == null)
					Log.d("TEST", "Connect ERROR!");
//					Toast.makeText(getCallingActivity(), "Connect ERROR!", Toast.LENGTH_SHORT).show();
					
				receiveService.receive(handler);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		// onPostExecute displays the results of the AsyncTask.
		// @Override
		// protected void onPostExecute(Socket result) {
		// socket = result;
		// receiveService.receive(handler);
		// }
	}

	private class SendTask extends AsyncTask<String, Void, Void> {
		// params comes from the execute() call
		@Override
		protected Void doInBackground(String... params) {
			try {
				Log.d("TEST", "SendTask");
				sendService = new SendService(socket);
				sendService.write(params[0]);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(Void result) {
			editTextInput.setText("", TextView.BufferType.NORMAL);
		}
	}

	@Override
	public void onInit(int status) {
		Toast.makeText(this, "tts init", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStop() {
//		if (mTTS != null) {
//			mTTS.stop();
//			mTTS.shutdown();
//		}
		super.onStop();
	}
	
	@Override
	public void finish() {
		super.finish();
	}
}